﻿using Kiwi.DataModel;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Linq;

namespace Kiwi.ViewModel
{
    public class CbNewsViewModel : ViewModelBase
    {

        protected override string RssUrl
        {
            get
            {
                return base.RssUrl;
            }
        }

        protected override void Request()
        {
            WebClient client = new WebClient();
            client.OpenReadCompleted += ReadRSSCompleted;
            client.OpenReadAsync(new Uri(RssUrl, UriKind.RelativeOrAbsolute));
        }

        void ReadRSSCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            XmlReader xmlreader = XmlReader.Create(e.Result);

            XDocument xdocument = XDocument.Load(xmlreader);

            var items = (from element in xdocument.Descendants("item")
                         select new NewsInfo()
                         {
                             Description = Regex.Replace(element.Element("description").Value.Replace("<br>", "\r\n"), "<(.[^><]*)>", ""),
                             Title = element.Element("title").Value,
                             Link = element.Element("link").Value,
                             Time = DateTime.Parse(element.Element("pubDate").Value)
                         });

            NewsCollection = new ObservableCollection<NewsInfo>(items);
            RaisePropertyChanged(() => NewsCollection);
        }

    }
}
